using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.customers;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.customers
{
    /// <summary>
    /// 逻辑删除客户命令处理器
    /// </summary>
    public class DeleteCustomerCommandHandler : IRequestHandler<DeleteCustomerCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<Customer> _customerRepository;
        private readonly ILogger<DeleteCustomerCommandHandler> _logger;

        public DeleteCustomerCommandHandler(
            IBaseRepository<Customer> customerRepository,
            ILogger<DeleteCustomerCommandHandler> logger)
        {
            _customerRepository = customerRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理逻辑删除客户命令
        /// </summary>
        /// <param name="request">删除客户命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<bool>> Handle(DeleteCustomerCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始逻辑删除客户，ID: {CustomerId}", request.Id);

                // 检查客户是否存在且未被删除
                var existingCustomer = await _customerRepository.GetAll()
                    .FirstOrDefaultAsync(c => c.Id == request.Id && !c.IsDeleted, cancellationToken);

                if (existingCustomer == null)
                {
                    _logger.LogWarning("客户不存在或已被删除，ID: {CustomerId}", request.Id);
                    return ApiResult<bool>.Error("客户不存在或已被删除");
                }

                // 检查客户状态，如果为启用状态则不允许删除
                if (existingCustomer.Status == "启用")
                {
                    _logger.LogWarning("无法删除启用状态的客户，ID: {CustomerId}, 名称: {CustomerName}, 状态: {Status}", 
                        request.Id, existingCustomer.Name, existingCustomer.Status);
                    return ApiResult<bool>.Error("无法删除启用状态的客户，请先停用后再删除");
                }

                // 检查是否有下级客户
                var hasSubordinateCustomers = await _customerRepository.GetAll()
                    .AnyAsync(c => c.SuperiorCustomerId == request.Id && !c.IsDeleted, cancellationToken);

                if (hasSubordinateCustomers)
                {
                    _logger.LogWarning("无法删除有下级客户的客户，ID: {CustomerId}, 名称: {CustomerName}", 
                        request.Id, existingCustomer.Name);
                    return ApiResult<bool>.Error("无法删除有下级客户的客户，请先处理下级客户关系");
                }

                // 执行逻辑删除（软删除）
                existingCustomer.IsDeleted = true;
                existingCustomer.UpdatedTime = DateTime.Now;
                existingCustomer.UpdatedBy = 1;

                // 执行更新操作
                var result = await _customerRepository.UpdateAsync(existingCustomer);

                if (result > 0)
                {
                    _logger.LogInformation("成功逻辑删除客户，ID: {CustomerId}, 名称: {CustomerName}", 
                        request.Id, existingCustomer.Name);
                    
                    return ApiResult<bool>.Success(true, "客户删除成功");
                }
                else
                {
                    _logger.LogError("逻辑删除客户失败，ID: {CustomerId}, 名称: {CustomerName}", 
                        request.Id, existingCustomer.Name);
                    
                    return ApiResult<bool>.Error("客户删除失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "逻辑删除客户时发生异常，ID: {CustomerId}", request.Id);
                
                return ApiResult<bool>.Error($"删除客户时发生异常: {ex.Message}");
            }
        }
    }
}
